﻿using System;
using System.Collections;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.Serialization;

namespace RakutenCrawler.ConfigClass
{
    public class Match
    {
        [XmlAttribute("pattern")]
        public string Pattern = string.Empty;
        [XmlAttribute("isMatchExact")]
        public bool IsMatchExact;

        public bool IsMatch(string input)
        {
            if (IsMatchExact)
                return Pattern.Equals(input);

            var regex = new Regex(Pattern);
            return regex.Match(input).Success;
        }
    }

    public class LinkConfig
    {
        [XmlAttribute("class")]
        public string Class = string.Empty;

        private string _configFile;

        [XmlAttribute("config-file")]
        public string ConfigFile
        {
            get
            {
                if (string.IsNullOrEmpty(_configFile))
                {
                    _configFile = Guid.ToString() + ".xml";
                }

                return _configFile;
            }
            set { _configFile = value; }
        }

        [XmlAttribute("guid")]
        public Guid Guid = Guid.Empty;

        [XmlArray("matches")]
        [XmlArrayItem("match", typeof(Match))]
        public ArrayList Matches;

        public bool IsSatisfy(string url)
        {
            foreach (var match in Matches.Cast<Match>())
            {
                if (match.IsMatch(url))
                    return true;
            }

            return false;
        }

        public string BuildPath()
        {
            if (string.IsNullOrEmpty(ConfigFile))
                throw new FileNotFoundException("Not specified config file path");

            var configFolder = ConfigurationManager.AppSettings["XmlConfigFolder"];
            if (string.IsNullOrEmpty(configFolder))
                configFolder = "Config";

            return Path.Combine(configFolder, ConfigFile);
        }
    }
}
